Learning Flex Basics (Part 1): Creating Your First Flex Application
Table of Contents
- Introduction
- A Brief Overview of Macromedia Flex
- Building the Application
- Create the Application Object
- Add a Panel for the Application Layout
- Add a Label for the View Header
- Add an Array of Objects to Define the Coffee Blends
- Add a ComboBox to Display the Coffee Blends
- Add a Text Control to Display the Description
- Add a Button to Add a Coffee Blend to the Shopping Cart
- Add a List Control for the Shopping Cart
- Add a Script to Handle the Button Click Event
- Complete Code Listing for firstapp.mxml
- Where to Go From Here
Add a Script to Handle the Button Click Event
The final step of the tutorial is to add an ActionScript function to handle the click event on the Button. For this simple application, add the function in a Script block.
The ActionScript code inside the Script block will be wrapped in a <![CDATA[ ]]> wrapper,
which instructs the XML parser to pass the contents of the wrapper through without parsing
them. This technique is standard XML practice, used here in case the script contains any
characters (such as a < symbol) that the parser might misinterpret
as XML code. As it happens, the code here will contain no such reserved characters,
but it's good to get in the habit of wrapping embedded script code in CDATA
just in case—it does no harm, and also saves the parser the trouble of parsing
non-XML code.
The ActionScript here is quite simple. The general syntax for functions is:
function functionName(parameter1:dataType...):returnDataType
{
[ActionScript statements]
}
In the addToCart() function, use the addItem() method
of the List class, which takes the parameters label and data.
The arguments you pass are simply the label and data properties of the
selected item in the ComboBox.
-
After the Array block, insert a Script block with a
CDATAwrapper nested inside:<mx:Script> <![CDATA[]]> </mx:Script>
-
Inside the CDATA wrapper, add an ActionScript function called
addToCart()that returns nothing;:function addToCart():Void { } -
Inside the function block, use the addItem method for the cart List to add the label and data properties of the selected item in the ComboBox:
cart.addItem(coffeeCombo.selectedItem.label,coffeeCombo.selectedItem.data;
- Save the file and test it in a web browser (for information on how to browse MXML files, see the first page in this tutorial).